package factory;

import dao.HelloDao;
import dao.impl.HelloDaoImpl;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Properties;
import java.util.Map;

public class BeanFactory {
    private static Properties properties;
    private static volatile Map<String,Object> cache = new HashMap<>();
    static {
        properties = new Properties();
        try {
            properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("factory.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Object getHelloDao(String beanName){

        //判断缓存中是否存在这个bean
        //双重检查锁
        if(!cache.containsKey(beanName)){
            synchronized (BeanFactory.class){
                if (!cache.containsKey(beanName)){
                    try {
                        String value = properties.getProperty(beanName);
                        System.out.println(value);
                        //通过反射，因为我们已经获取到了全类名
                        Class clazz = Class.forName(value);
                        Object object = clazz.getConstructor(null).newInstance(null);
                        //将bean存入缓存
                        cache.put(beanName, object);
                        return object;
                    } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        return cache.get(beanName);
    }
}
